import { Inject, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcryptjs';
import { User } from '../entity/user.entity';
import { RedisService } from '@midwayjs/redis';
import { JwtService } from '@midwayjs/jwt';
import { CaptchaCodeService } from './captcha.service';
import { decryptAes } from '../utils';

@Provide()
export class AuthService {
    @InjectEntityModel(User)
    userModel: Repository<User>;

    @Inject()
    jwt: JwtService;

    @Inject()
    captchaService: CaptchaCodeService

    @Inject()
    redisService: RedisService;

    /**
     * 用户登录
     */
    async login(params: any): Promise<any> {
        await this.captchaService.checkCaptcha(params.captchaId, params.captchaCode)
        const user = await this.userModel.createQueryBuilder('user')
            .addSelect('user.password')
            .where('user.username = :username', { username: params.username })
            .andWhere('user.delFlag = :delFlag', { delFlag: 0 })
            .getOne()
        // const user = await this.userModel.findOneBy({
        //     username: params.username,  delFlag: 0
        // });
        const password = params.password
        const pw = decryptAes(password)
        const isTrue = bcrypt.compareSync(pw, user.password)
        if (user && isTrue) {
            const jwt = await this.jwt.sign({ uid: user.id, userName: user.username })
            const redis = await this.redisService.get(`userToken:${user.id}`)
            if (redis) {
                this.redisService.del(`userToken:${user.id}`)
            } else {
                this.redisService.set(`userToken:${user.id}`, jwt, 'EX', 43200)
            }
            return {
                ...user,
                token: jwt
            }
        }
        throw new Error("账号或密码错误！")
    }
} 